<?php

// 登录
// POST admin.rbac.manager.login

namespace app\api\resource\admin\rbac\manager;
use think\Db;
use think\facade\Session;
use app\common\validate\Manager as ManagerValidate;

class Login
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '登录';
    // 参数
    public $_param  = [
        'username' => '用户名',
        'password' => '登录密码',
    ];

    public function run(&$request)
    {
        $params = $request->param();
        
        $validate = new ManagerValidate;
        if ( !$validate->scene('login')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $manager = Db::name('rbac_manager')
        ->where('username',$params['username'])
        ->where( 'password',md5($params['password']) )
        ->field('password',true)
        ->find();

        if ( is_null($manager) )     return [401,'用户名或密码错误'];
        if (1 == $manager['status']) return [423,'帐号被限制使用'];

        // 更新活跃时间
        Db::name('rbac_manager')->where('id',$manager['id'])->update(['update_time'=>time()]);

        // 写入SESSION
        Session::set('manager',$manager);

        return [201,'登录成功'];
    }
}